package com.zhangxiaofanfan.hotcode.second;

import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.TreeMap;

/**
 * <a href="https://leetcode.cn/problems/top-k-frequent-elements/?envType=study-plan-v2&envId=top-100-liked">347. 前 K 个高频元素</a>
 *
 * @date 2024-07-13 03:14:13
 * @author zhangxiaofanfan
 */
public class HotCode075 {
    public static void main(String[] args) {
        HotCode075 hotCode = new HotCode075();
        int[] nums = {1,2};
        int k = 2;
        System.out.println(Arrays.toString(hotCode.topKFrequent(nums, k)));
    }

    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        int[] result = new int[k];
        Arrays.stream(nums).forEach(num -> map.put(num, map.getOrDefault(num, 0) + 1));
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>((node1, node2) -> Integer.compare(map.get(node2), map.get(node1)));
        map.keySet().stream().forEach(priorityQueue::add);
        for (int i = 0; i < k; i++) {
            result[i] = priorityQueue.poll();
        }
        return result;
    }
}
